package me.xhh.mail;
import java.util.Map;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import me.xhh.mail.TemplateHandler.MailTemplate;
import me.xhh.utils.Util;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Mail {
private static final String SMTP_HOST_NAME = "TODO";
private static final String SMTP_AUTH_USER = "TODO";
private static final String SMTP_AUTH_PWD = "TODO";
private static final String SMTP_SEND_FROM = "TODO";
private static final Logger log = LoggerFactory.getLogger(Mail.class);
private static void postMail(String[] recipients, String[] replyTo, String subject, String message, String fromEmail,
boolean htmlMail) throws MessagingException, AuthenticationFailedException {
boolean debug = false;
Properties props = new Properties();
// use this to prevent the [MessagingException: 501 Syntax: HELO hostname]
props.put("mail.smtp.localhost", SMTP_HOST_NAME);
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator(SMTP_AUTH_USER, SMTP_AUTH_PWD);
// use Session.getInstance instead of Session.getDefaultInstance to
// get rid of [SecurityException: Access to default session denied]
Session session = Session.getInstance(props, auth);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// check and set the from
if (fromEmail == null)
fromEmail = SMTP_SEND_FROM;
InternetAddress addressFrom = new InternetAddress(fromEmail);
msg.setFrom(addressFrom);
// set recipients
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
addressTo[i] = new InternetAddress(recipients[i]);
msg.setRecipients(Message.RecipientType.TO, addressTo);
// check and set reply-to
if (replyTo != null && replyTo.length > 0) {
Address[] replyToAddresses = new Address[replyTo.length];
for (int i = 0; i < replyTo.length; i++)
replyToAddresses[i] = new InternetAddress(replyTo[i]);
msg.setReplyTo(replyToAddresses);
}
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, htmlMail ? "text/html;charset=utf-8" : "text/plain;charset=utf-8");
// send mail
Transport.send(msg);
}
public static void sendInThread(String recipient, MailTemplate template, Map<String, Object> mailData) {
sendInThread(new String[]{recipient}, template, mailData);
}
public static void sendInThread(final String[] recipients, final MailTemplate template, final Map<String, Object> mailData) {
new Thread() {
public void run() {
send(recipients, template, mailData);
}
}.start();
}
public static boolean send(String recipient, MailTemplate template, Map<String, Object> mailData) {
return send(new String[]{recipient}, template, mailData);
}
public static boolean send(String[] recipients, MailTemplate template, Map<String, Object> mailData) {
log.info("sending email with template: {}", template);
String data;
try {
data = TemplateHandler.processTemplate(template, mailData);
} catch (Exception e) {
log.error("Failed to process the email template: " + template, e);
return false;
}
int pos = data.indexOf("\n");
String subject = data.substring(0, pos).trim();
String message = data.substring(pos + 1).trim();
return send(recipients, subject, message);
}
public static boolean send(String[] recipients, String subject, String message) {
boolean sent;
if (Util.DEBUG) {
sent = true;
log.debug("[Mail.send] Development env found, email is not sent actually.");
} else {
try {
postMail(recipients, null, subject, message, null, false);
sent = true;
} catch (Exception e) {
log.error("Failed to postMail! Subject: " + subject, e);
sent = false;
}
}
// log the email details
Object[] logArgs = {sent ? "Email sent to:" : "Failed to send email to:", StringUtils.join(recipients, ','), subject, message};
if (sent) {
log.info("{} {}\nSubject: {}\n'''\n{}\n'''", logArgs);
} else {
log.error("{} {}\nSubject: {}\n'''\n{}\n'''", logArgs);
}
return true;
}
}
/**
* SimpleAuthenticator is used to do simple authentication when the SMTP server requires it.
*/
class SMTPAuthenticator extends javax.mail.Authenticator {
private String username;
private String password;
public SMTPAuthenticator(String smtpAuthUser, String smtpAuthPwd) {
this.username = smtpAuthUser;
this.password = smtpAuthPwd;
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}